package com.webshop.servlet;

import com.webshop.Dao.ProductDao;
import com.webshop.Dao.UserDao;
import com.webshop.domain.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("userid"));
        User user = UserDao.getUser(id);
        String items = user.getItemsid();
        List<String> list = new ArrayList<String>(Arrays.asList(items.split("#")));
        Iterator iterator = list.iterator();
        String itemsid=null;
        for(int i=0;i<list.size();i++){
            if(list.get(i).equals(req.getParameter("id")))
                list.remove(i);
        }
        if (list.size()>0){
            itemsid = list.get(0);
            for (int i=1;i<list.size();i++){
                itemsid = itemsid+"#"+list.get(i);
            }
        }
        user.setItemsid(itemsid);
        UserDao.updateUesr(user);
        ProductDao.delete(Integer.parseInt(req.getParameter("id")));
        resp.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


}
